﻿/*userRealNameAuthenticationCtrl Controllers*/
//实名认证
app.controller('userRealNameAuthenticationCtrl', ['$scope', '$filter','$http', '$state', '$stateParams', '$location', '$ngBootbox', 'dataService', 'valueservice', 'azureBlob',
function ($scope,$filter, $http, $state, $stateParams, $location, $ngBootbox, dataService, valueservice, azureBlob) {
    var userId = $scope.userId = window.localStorage.id;
    // $scope.carCode = (window.localStorage.carCode == "null") ? " " : window.localStorage.carCode;

    var refreshPage = function (userId) {
        var LicenseNameStr = ['RealHead', 'DrivingLicense', 'VehicleLicense', 'IDCard', 'TrailerLicense', 'CarImage'];
        LicenseNameStr.forEach(function (item) {
            $('#uploader' + item).attr('disabled', 'true');
            //$('#colorUpLoad' + item).removeAttr("style", "color:#ee3939");
            $('#colorUpLoad' + item).removeClass("text-danger");
            //$('#cancle' + item).attr('style', 'display:none;');
            $('#cancle' + item).addClass('none');
        });
        angular.forEach(angular.element("input[type='file']"), function (inputElem) { angular.element(inputElem).val(null); });
        dataService.getRealNameInfo(userId).then(function (res) {
            res = res.data.info;
            $scope.carCode = res.carCode;
            $scope.realNameCheckState = valueservice.getRealNameState()[res.state].text;

            $scope.realHeadImage = res.realHeadImage || '../src/img/Group.png';
            $scope.realHeadState = valueservice.getRealNameState()[res.realHeadState].text;
            $scope.realHeadStateSubmit = res.realHeadState;
            $('#RealHead').attr('src', $scope.realHeadImage);

            $scope.drivingLicenseImage = res.drivingLicenseImage || '../src/img/Group.png';
            $scope.drivingLicenseState = valueservice.getRealNameState()[res.drivingLicenseState].text;
            $scope.drivingLicenseStateSubmit = res.drivingLicenseState;
            $('#DrivingLicense').attr('src', $scope.drivingLicenseImage);

            $scope.vehicleLicenseImage = res.vehicleLicenseImage || '../src/img/Group.png';
            $scope.vehicleLicenseState = valueservice.getRealNameState()[res.vehicleLicenseState].text;
            $scope.vehicleLicenseStateSubmit = res.vehicleLicenseState;
            $('#VehicleLicense').attr('src', $scope.vehicleLicenseImage);

            $scope.idCardImage = res.idCardImage || '../src/img/Group.png';
            $scope.idCardState = valueservice.getRealNameState()[res.idCardState].text;
            $scope.idCardStateSubmit = res.idCardState;
            $('#IDCard').attr('src', $scope.idCardImage);

            $scope.trailerLicenseImage = res.trailerLicenseImage || '../src/img/Group.png';
            $scope.trailerLicenseState = valueservice.getRealNameState()[res.trailerLicenseState].text;
            $scope.trailerLicenseStateSubmit = res.trailerLicenseState;
            $('#TrailerLicense').attr('src', $scope.trailerLicenseImage);

            $scope.carImage = res.vehiclePhotoImage || '../src/img/Group.png';
            $scope.carImageState = valueservice.getRealNameState()[res.vehiclePhotoState].text;
            $scope.carImageStateSubmit = res.vehiclePhotoState;
            $('#CarImage').attr('src', $scope.carImage);
        });
        
    }
    refreshPage(userId);
    //删除
    $scope.delState = function (realNameType) {
        $ngBootbox.confirm('确认删除此证件么？').then(function () {
            dataService.ModifyRealNameInfoByUserId($scope.userId, realNameType, "", true)
            //$http.post(Mustache.render("/api/" + "User/ModifyRealNameInfoByUserId?userId={{userId}}&type={{type}}&imageUri={{imageUri}}&forceEdit={{forceEdit}}", { userId: $scope.userId, type: realNameType, imageUri: "", forceEdit: true }))
            .then(function (res) {
                //console.info(res);
                refreshPage(userId);
            }, function (err) { })
        }, function () { return; })
    }

    //通过、不通过、撤销通过 操作
    $scope.submitUserInfo = function (state, stateName) {
        var bootInfo;
        if (state == 4) { bootInfo = '不通过'; } else if (state == 3) { bootInfo = '通过'; } else if (state == 2) { bootInfo = '撤销通过'; }
        $ngBootbox.confirm('确认' + bootInfo + '此证件么？').then(function () {
            
            var list = {
                UserId: $scope.userId,
                CarCode: $scope.carCode,
                DrivingLicenseKeyStatus: stateName == 'DrivingLicenseKeyStatus' ? state : $scope.drivingLicenseStateSubmit,
                RealHeadKeyStatus: stateName == 'RealHeadKeyStatus' ? state : $scope.realHeadStateSubmit,
                IdCardKeyStatus: stateName == 'IdCardKeyStatus' ? state : $scope.idCardStateSubmit,
                VehicleLicenseKeyStatus: stateName == 'VehicleLicenseKeyStatus' ? state : $scope.vehicleLicenseStateSubmit,
                TrailerLicenseKeyStatus: stateName == 'TrailerLicenseStatus' ? state : $scope.trailerLicenseStateSubmit,
                VehiclePhotoKeyStatus: stateName == 'CarImageStatus' ? state : $scope.carImageStateSubmit
            };
            dataService.putUserRealNameCertificationStatus(list).then(function (res) {
                refreshPage(userId);
            }, function (err) { });
        }, function () { return; })
    }
        
    //下载
    $scope.download = function (imageUrl) {
        //window.location.href = imageUrl;
        //var url = "https://capacitycloudstorage.blob.core.chinacloudapi.cn/realname-container/2015100510515483.jpg";
        saveFile(imageUrl);
    }
    // Download a file form a url.
    function saveFile(url) {
        // Get file name from url.
        var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
        var xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onload = function () {
            var a = document.createElement('a');
            a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
            a.download = filename; // Set the file name.
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            delete a;
        };
        xhr.open('GET', url);
        xhr.send();
    }
    //获取sas url
    dataService.AquireStorageSharedSigniture('avatar-container')
    //$http.get(Mustache.render("/api/" + "Storage/AquireStorageSharedSigniture?containerName={{containerName}}&expireTime={{expireTime}}", { containerName: 'avatar-container' }))
    .then(function (res) {
         $scope.sasUrl = res.data.storageSharedSigniture;
    });
    
    $('#realHead').bind('change', 'RealHead', handleFileSelect);
    $('#uploaderDriving').bind('change', 'DrivingLicense', handleFileSelect);
    $("#vehicleLicense").bind('change', 'VehicleLicense', handleFileSelect);
    $('#idCard').bind('change', 'IDCard', handleFileSelect);
    $('#trailerLicense').bind('change', 'TrailerLicense', handleFileSelect);
    $('#carImage').bind('change', 'CarImage', handleFileSelect);
    function handleFileSelect(e) {
        var files = e.target.files;
        if (files.length > 0) {
            if (!/image\/(gif|jpeg|jpg|png|bmp)/.test(files[0].type)){
                $ngBootbox.alert("请选择图片格式文件");
            } else {
                if (files[0].size > 1048576) {
                    $ngBootbox.alert("上传图片大小需小于1M!");
                } else {
                    //$("#colorUpLoad" + e.data).attr("style", "color:#ee3939");
                    $("#colorUpLoad" + e.data).addClass("text-danger");
                    $('#uploader' + e.data).removeAttr('disabled');
                    //$('#cancle' + e.data).removeAttr('style', 'display:none;')
                    $('#cancle' + e.data).removeClass('none')
                    switch (e.data) {
                        case 'VehicleLicense':
                            return $scope.selectedFileVehicleLicense = files[0],
                                   $scope.submitVehicleLicenseUrl = handleFileSelectfunc('VehicleLicense', $scope.selectedFileVehicleLicense.name, files);
                        case 'DrivingLicense':
                            return $scope.selectedFileDrivingLicense = files[0],
                                   $scope.submitDrivingLicenseUrl = handleFileSelectfunc('DrivingLicense', $scope.selectedFileDrivingLicense.name, files);
                        case 'IDCard':
                            return $scope.selectedFileIdCard = files[0],
                                   $scope.submitIdCardUrl = handleFileSelectfunc('IDCard', $scope.selectedFileIdCard.name, files);
                        case 'RealHead':
                            return $scope.selectedFileRealHead = files[0],
                            $scope.submitRealHeadUrl = handleFileSelectfunc('RealHead', $scope.selectedFileRealHead.name, files);
                        case 'TrailerLicense':
                            return $scope.selectedFileTrailerLicense = files[0],
                                $scope.submitTrailerLicenseUrl = handleFileSelectfunc('TrailerLicense', $scope.selectedFileTrailerLicense.name, files);
                        case 'CarImage':
                            return $scope.selectedFileCarImage = files[0],
                                $scope.submitCarImageUrl = handleFileSelectfunc('CarImage', $scope.selectedFileCarImage.name, files);
                    }
                }//end if 图片大小
            }//end if 是否选择文件格式：图片
        }//end if 是否已选择文件控制
    };
    function handleFileSelectfunc(imageName, name, files) {
        var baseUrl = $scope.sasUrl;
        var indexOfQueryStart = baseUrl.indexOf("?");
        var objUrl = getObjectURL(files[0]);
        $('#' + imageName).attr('src', objUrl);
        $('#enlargeImage' + imageName).attr('href', objUrl);
        var today = new Date();
        var formatDate = $filter('date')(today, 'yyyyMMddHHmms');
        var rr = name.indexOf(".");
        name = formatDate + Math.round(Math.random() * 10000).toString() + name.substring(rr);
        return baseUrl.substring(0, indexOfQueryStart) + '/' + name + baseUrl.substring(indexOfQueryStart);
    };
    //建立一個可存取到該file的url
    function getObjectURL(file) {
        var urlImg = null;
        if (window.createObjectURL != undefined) { // basic
            urlImg = window.createObjectURL(file);
        } else if (window.URL != undefined) { // mozilla(firefox)
            urlImg = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) { // webkit or chrome
            urlImg = window.webkitURL.createObjectURL(file);
        }
        return urlImg;
    }

    //取消所选图片(点击事件)
    $scope.cancleImageUpload = function (imageName,imageUrl,inputFileId) {
        $('#uploader' + imageName).attr('disabled', 'true');
        //$('#cancle' + imageName).attr('style', 'display:none;');none
        $('#cancle' + imageName).addClass("none");
        //$('#colorUpLoad' + imageName).removeAttr("style", "color:#ee3939");
        $('#colorUpLoad' + imageName).removeClass("text-danger");
        $('#' + imageName).attr('src', imageUrl);
        $('#enlargeImage' + imageName).attr('href', imageUrl);
        angular.element("#" + inputFileId).val(null);
        switch (imageName) {
            case 'RealHead': return $scope.submitRealHeadUrl = '';
            case 'DrivingLicense': return $scope.submitDrivingLicenseUrl = '';
            case 'VehicleLicense': return  $scope.submitVehicleLicenseUrl = '';
            case 'IDCard': return $scope.submitIdCardUrl = '';
            case 'TrailerLicense': $scope.submitTrailerLicenseUrl = '';
            case 'CarImage': return $scope.submitCarImageUrl = '';
        }
    }
    //上传点击事件
    $scope.upLoad = function (imageName) {
        switch (imageName) {
            case 'VehicleLicense': return upload($scope.submitVehicleLicenseUrl, $scope.selectedFileVehicleLicense, 3);
            case 'DrivingLicense': return upload($scope.submitDrivingLicenseUrl, $scope.selectedFileDrivingLicense, 2);
            case 'IDCard': return upload($scope.submitIdCardUrl, $scope.selectedFileIdCard, 1);
            case 'RealHead': return upload($scope.submitRealHeadUrl, $scope.selectedFileRealHead, 4);
            case 'TrailerLicense': return upload($scope.submitTrailerLicenseUrl, $scope.selectedFileTrailerLicense, 7);
            case 'CarImage': return upload($scope.submitCarImageUrl, $scope.selectedFileCarImage, 8);
        }
    }
    
    /**
     * 上传
     */
    function upload(submitUri, selectedFile, result) {
        if (submitUri !== null && selectedFile !== null && result !== null) {
            azureBlob.upload({
                baseUrl: submitUri,
                sasToken: 'avatar-container',
                file: selectedFile,
                progress: function (data, status) {
                    //console.log('test progress data', data);
                    //console.log('test progress status', status);
                },
                complete: function (data, status) {
                    //console.log('test complete data', data);
                    //console.log('test complete status', status);
                    //console.info('result', result);
                    var imageUriSubmit = encodeURIComponent(submitUri.split("?", 1).join());
                    dataService.ModifyRealNameInfoByUserId($scope.userId, result, imageUriSubmit, true )
                    //$http.post(Mustache.render("/api/" + "User/ModifyRealNameInfoByUserId?userId={{userId}}&type={{type}}&imageUri={{imageUri}}&forceEdit={{forceEdit}}", { userId: $scope.userId, type: result, imageUri: imageUriSubmit, forceEdit: true }))
                    .then(function (res) {
                        //console.info(res);
                        refreshPage($scope.userId);
                    }, function (err) { })
                },
                error: function (xhr, desc, err) {
                    //console.log('test error desc', desc);
                    //console.log('test error err', err);
                },
                blockSize: 1024 * 32,
            });
        } else {
            $ngBootbox.alert("请选择图片");
        }
    };
   
}])